package com.ruoyi.system.domain;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.*;

public class MealOrderExportUtil {

    /**
     * 按培训分组导出订餐数据到Excel
     *
     * @param response HTTP响应
     * @param groupedData 按培训分组的数据
     * @param fileName 文件名
     * @throws IOException IO异常
     */
    public static void exportGroupedExcel(HttpServletResponse response,
                                          Map<String, List<MealOrderExportVO>> groupedData,
                                          String fileName) throws IOException {
        Workbook workbook = new XSSFWorkbook();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        // 为每个培训创建一个工作表
        for (Map.Entry<String, List<MealOrderExportVO>> entry : groupedData.entrySet()) {
            String trainingName = entry.getKey();
            List<MealOrderExportVO> dataList = entry.getValue();

            // 创建工作表（限制工作表名称长度）
            String sheetName = trainingName.length() > 31 ? trainingName.substring(0, 31) : trainingName;
            Sheet sheet = workbook.createSheet(sheetName);

            // 创建表头
            createHeaderRow(sheet, dataList.isEmpty() ? (MealOrderExportVO) Collections.emptyList() : dataList.get(0));

            // 填充数据
            fillDataRows(sheet, dataList, dateFormat);
        }

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=\"" +
                java.net.URLEncoder.encode(fileName, "UTF-8") + "\"");

        // 写入响应流
        OutputStream out = response.getOutputStream();
        workbook.write(out);
        out.flush();
        out.close();
        workbook.close();
    }

    /**
     * 创建表头行
     */
    private static void createHeaderRow(Sheet sheet, MealOrderExportVO sampleData) {
        Row headerRow = sheet.createRow(0);

        // 固定列头
        String[] fixedHeaders = {"序号", "培训名称", "培训时间", "姓名", "员工编号", "性别", "部门", "电话", "邮箱"};
        for (int i = 0; i < fixedHeaders.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(fixedHeaders[i]);
            cell.setCellStyle(createHeaderCellStyle(sheet.getWorkbook()));
        }

        // 动态列头（根据培训期间的日期生成）
        if (sampleData != null && sampleData.getStartDate() != null && sampleData.getEndDate() != null) {
            Calendar cal = Calendar.getInstance();
            cal.setTime(sampleData.getStartDate());

            Calendar endCal = Calendar.getInstance();
            endCal.setTime(sampleData.getEndDate());

            int columnIndex = fixedHeaders.length;
            while (!cal.after(endCal)) {
                Date date = cal.getTime();
                String dateStr = new SimpleDateFormat("yyyy-MM-dd").format(date);

                // 午餐列
                Cell lunchCell = headerRow.createCell(columnIndex++);
                lunchCell.setCellValue(dateStr + "午餐");
                lunchCell.setCellStyle(createHeaderCellStyle(sheet.getWorkbook()));

                // 晚餐列
                Cell dinnerCell = headerRow.createCell(columnIndex++);
                dinnerCell.setCellValue(dateStr + "晚餐");
                dinnerCell.setCellStyle(createHeaderCellStyle(sheet.getWorkbook()));

                cal.add(Calendar.DAY_OF_MONTH, 1);
            }
        }
    }

    /**
     * 填充数据行
     */
    private static void fillDataRows(Sheet sheet, List<MealOrderExportVO> dataList, SimpleDateFormat dateFormat) {
        int rowNum = 1;
        String[] fixedFields = {"seq", "trainingName", "trainingTime", "employeeName", "employeeNo", "sex", "dept", "phone", "email"};

        for (MealOrderExportVO data : dataList) {
            Row row = sheet.createRow(rowNum++);

            // 填充固定列数据
            for (int i = 0; i < fixedFields.length; i++) {
                Cell cell = row.createCell(i);
                Object value = getFieldValue(data, fixedFields[i]);
                setCellValue(cell, value);
            }

            // 填充动态列数据（用餐详情）
            if (data.getDailyMeals() != null) {
                // 根据培训日期范围填充用餐数据
                if (data.getStartDate() != null && data.getEndDate() != null) {
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(data.getStartDate());

                    Calendar endCal = Calendar.getInstance();
                    endCal.setTime(data.getEndDate());

                    int columnIndex = fixedFields.length;
                    while (!cal.after(endCal)) {
                        Date date = cal.getTime();
                        String dateStr = dateFormat.format(date);

                        // 午餐数据
                        String lunchKey = dateStr + "_午餐";
                        Cell lunchCell = row.createCell(columnIndex++);
                        lunchCell.setCellValue(data.getDailyMeals().getOrDefault(lunchKey, ""));

                        // 晚餐数据
                        String dinnerKey = dateStr + "_晚餐";
                        Cell dinnerCell = row.createCell(columnIndex++);
                        dinnerCell.setCellValue(data.getDailyMeals().getOrDefault(dinnerKey, ""));

                        cal.add(Calendar.DAY_OF_MONTH, 1);
                    }
                }
            }
        }
    }

    /**
     * 获取对象字段值
     */
    private static Object getFieldValue(Object obj, String fieldName) {
        try {
            Field field = obj.getClass().getDeclaredField(fieldName);
            field.setAccessible(true);
            return field.get(obj);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 设置单元格值
     */
    private static void setCellValue(Cell cell, Object value) {
        if (value == null) {
            cell.setCellValue("");
        } else if (value instanceof Number) {
            cell.setCellValue(((Number) value).doubleValue());
        } else if (value instanceof Date) {
            cell.setCellValue(new SimpleDateFormat("yyyy-MM-dd").format((Date) value));
        } else {
            cell.setCellValue(value.toString());
        }
    }

    /**
     * 创建表头单元格样式
     */
    private static CellStyle createHeaderCellStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setBold(true);
        style.setFont(font);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        return style;
    }
}